//
//  ZMProductViewController.swift
//  LoveBeen
//
//  Created by pg on 2017/8/8.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import GPUImage

class ZMProductViewController: UITableViewController {

    //接受外部传入加入购物车中的所有的商品模型
    var selectedProductModelArr : [ZMProductsModel]?{
        didSet{
            //计算选中商品的数量
//            self.bottomView?.shopCarView.title = "0"
//            var num: Int = 0
//            for model in selectedProductModelArr!{
//                
//                num +=  model.buyNum
//            }
//            print("选中商品数量:\(num)")
//            self.bottomView?.shopCarView.title = "\(num)"
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.bottomView?.shopCarView.title = "0"
        var num: Int = 0
        for model in selectedProductModelArr!{
            
            num +=  model.buyNum
        }
      
        self.bottomView?.shopCarView.title = "\(num)"
        
    }
    
    var productModel: ZMProductsModel?{
        didSet{
            
        }
    }
    
    var bottomView: ZMBottomView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.tableView.tableHeaderView = self.headerView
        
        tableView.separatorStyle = .singleLine
        tableView.separatorColor = UIColor.lightGray
        //注册cell
        
        tableView.sectionHeaderHeight = 60
        tableView.bounces = false
        tableView.register(ProdectInfoCell.self, forCellReuseIdentifier: "cell")
        
        //添加底部view
//        view.addSubview(bottonView)
//        bottonView.snp.makeConstraints { (make) in
//            make.leading.bottom.trailing.equalToSuperview()
//            make.height.equalTo(60)
//            make.top.equalTo(tableView.snp.bottom)
//        }
        
       // tableView.tableFooterView = bottonView
        
        
        let temoview = ZMBottomView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - CGFloat(128), width: UIScreen.main.bounds.width, height: 64))
        self.bottomView = temoview
        temoview.productModel = self.productModel
        temoview.backgroundColor = UIColor.white
        tableView.addSubview(temoview)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationItem.title = productModel?.name
        
        self.headerimageview?.sd_setImage(with: URL(string: productModel!.img!))
        self.sectionView.title.text = productModel?.name
        self.sectionView.priceLabel.text = productModel?.price
        self.sectionView.market_priceLabel.text = productModel?.market_price
        
        self.tableView.reloadData()
    }
    
    
    fileprivate var headerimageview: UIImageView?
    
    //懒加载headerView
    fileprivate lazy var headerView : UIView = {
       
        let hdView = UIView()
        
        let imageview = UIImageView(image: #imageLiteral(resourceName: "v2_placeholder_full_size"))
        
        imageview.contentMode = .scaleAspectFill
      
        self.headerimageview = imageview
        
        hdView.addSubview(imageview)
        
        imageview.snp.makeConstraints({ (make) in
             make.top.equalTo(hdView).offset(10)
            make.leading.equalTo(hdView).offset(10)
            make.trailing.equalTo(hdView).offset(-10)
            make.bottom.equalTo(hdView).offset(-80)
            
        })
       hdView.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300)
        return hdView
    }()
   
    //MARK:- 组头视图
    fileprivate lazy var  sectionView : SectionHeaderView = {
        let section = SectionHeaderView()
        
       // section.backgroundColor = UIColor.orange
        
     //   section.bounds = CGRect(x: 0, y: 0, width: 200, height: 100)
        return section
    }()
   
   

     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return 3
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProdectInfoCell
        cell.backgroundColor = UIColor(white: 0.9, alpha: 1)
        cell.detailTextLabel?.textAlignment = .left
        cell.detailTextLabel?.backgroundColor = UIColor.orange
        cell.detailTextLabel?.bounds = CGRect(x: 0, y: 0, width: 300, height: 30)
        
        
        switch indexPath.row {
        case 0:
            cell.textLabel?.text = "品        牌"
            cell.subTitleLabel.text = productModel?.brand_name
        case 1:
            cell.textLabel?.text = "产品规格"
            cell.subTitleLabel.text = productModel?.specifics
        case 2:
            cell.textLabel?.text = "图文详情"
           // cell.detailTextLabel?.text = productModel?.brand_name
        default:
            cell.textLabel?.text = ""
        }
        
        return cell
    }
    

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        
        return sectionView
    }
}

//自定义底部view
class ZMBottomView: UIView {
    
    var productModel: ZMProductsModel?{
        didSet{
            self.addButtonView.count = productModel?.buyNum ?? 0
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    //MARK:- 懒加载提示视图
    fileprivate lazy var addlabel: UILabel = {
        let  label = UILabel(text: "添加商品:", fontSize: 15, textColor: UIColor.darkGray)
        label.sizeToFit()
        return label
    }()
    //MARK:-懒加载添加按钮视图
    fileprivate lazy var addButtonView: ZMAddToShoppingCarView = {
        
        let addview = ZMAddToShoppingCarView(frame: CGRect(x: 100, y: 20, width: 60, height: 20))
        addview.HiddenLeftView(isHidden: false)
        addview.count = self.productModel?.buyNum ?? 0
        return addview
    }()
    //懒加载购物车图片view
    fileprivate lazy var shopCarView : ZMCuteImageView = {
        let imageview = ZMCuteImageView()//UIImageView(frame: CGRect(x: 300, y: 10, width: 40, height: 40))
        let image = UIImage(named: "v2_shop_empty")
        imageview.image = image
    //  imageview.title = "0"
        
        return imageview
    }()
    
    func setupUI(){
        
        
        //添加label
        addSubview(addlabel)
        addlabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.leading.equalTo(self).offset(20)
        }
       //添加加好按钮
        addSubview(addButtonView)
        //添加购物车图标
        self.addSubview(self.shopCarView)
        shopCarView.setUp()
        //添加红色视图
        //shopCarView.addSubview(self.redView)

        shopCarView.snp.makeConstraints { (make) in
            make.trailing.bottom.equalTo(self).offset(-5)
            make.width.equalTo(60)
            make.height.equalTo(60)
        }
        
        
        addButtonView.addToShoppintCarViewButtonClickClosure = {[unowned self] (isaddbtn) in
            var num = self.productModel?.buyNum ?? 0
             var shopCarNum = (self.shopCarView.title as NSString).intValue
            if isaddbtn {
                num += 1
                shopCarNum += 1
                //发送添加通知
                NotificationCenter.default.post(name: NSNotification.Name(AddToShoppingCarViewNotification), object: nil, userInfo: ["model": self.productModel!])
                print("+")
            }else{
                num -= 1
                if num < 0 {
                    num = 0
                }
                shopCarNum -= 1
                if shopCarNum < 0 {
                    shopCarNum = 0
                }
                //发送添加通知
                NotificationCenter.default.post(name: NSNotification.Name(SubFromShoppingCarViewNotification), object: nil, userInfo: ["model": self.productModel!])
                print("-")
            }
            
           
            self.shopCarView.title = "\(shopCarNum)"
            
            
            self.addButtonView.count = self.productModel?.buyNum ?? 0
        }
        
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}





class  ProdectInfoCell: UITableViewCell {
    
    //添加自定义的子标题
    fileprivate lazy var subTitleLabel: UILabel = {
       let label = UILabel(text: "", fontSize: 15, textColor: UIColor.darkGray)
        
        label.textAlignment = .left
        label.sizeToFit()
        return label
    }()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: UITableViewCellStyle.value1, reuseIdentifier: reuseIdentifier)
        
        self.detailTextLabel?.textAlignment = .left
        
        self.contentView.addSubview(subTitleLabel)
        subTitleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalTo(contentView).offset(120)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


class SectionHeaderView: UIView {
    
    
    //MARK:- 懒加载title
    fileprivate lazy var title: UILabel = {
        let titleview = UILabel(text: "title", fontSize: 18, textColor: UIColor.black)
        
        titleview.sizeToFit()
        return titleview
    }()
    //MARK:- 懒加载价格label
    //懒加载 现价
    fileprivate lazy var priceLabel : UILabel  = {
        let label = UILabel(text: "现价", fontSize: 14, textColor: UIColor.red)
        
        label.sizeToFit()
        return label
        
    }()
    //懒加载 超时价格  market_price
    fileprivate lazy var market_priceLabel : UILabel  = {
        let label = UILabel(text: "原价", fontSize: 14, textColor: UIColor.lightGray)
        
        let line: UIView = UIView()
        label.addSubview(line)
        
        line.backgroundColor = UIColor.lightGray
        
        line.snp.makeConstraints({ (make) in
            make.center.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(1)
        })
        
        
        
        label.sizeToFit()
        return label
        
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        addSubview(title)
        title.snp.makeConstraints { (make) in
            make.top.leading.equalToSuperview().offset(10)
        }
        //加载价格label
        addSubview(priceLabel)
        priceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(title.snp.bottom).offset(10)
            make.leading.equalTo(title)
          //  make.bottom.equalToSuperview().offset(-10)
        }
        addSubview(market_priceLabel)
        market_priceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(priceLabel)
            make.leading.equalTo(priceLabel.snp.trailing).offset(10)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
}


